package com.studycloud.controller;

import com.studyclud.entity.Payment;
import com.studyclud.result.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

import static com.studyclud.constant.ConstantUrl.PAYMENT_URL;

/**
 * @author JP
 */
@RestController
@Slf4j
public class OrderController
{
    @Resource
    private RestTemplate restTemplate;

    @GetMapping(value = "/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment)
    {
        return restTemplate.postForObject("HTTP://"+PAYMENT_URL+"/payment/create",payment,CommonResult.class);
    }

    /**
     * 使用 => getForObject
     * @param id
     * @return
     */
    @GetMapping(value = "/consume/payment/getPaymenById/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id)
    {
        return restTemplate.getForObject("HTTP://"+PAYMENT_URL+"/payment/getPaymenById/"+id,CommonResult.class);
    }

    /**
     * 使用 => getForEntity
     * 有 bug
     * @param id
     * @return
     */
    @GetMapping(value = "/consume/payment/getPaymenById2/{id}")
    public CommonResult<Payment> getPaymentById2(@PathVariable("id") Long id)
    {
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity("HTTP://"+PAYMENT_URL+"/payment/getPaymenById/"+id, CommonResult.class);

        if (entity.getStatusCode().is2xxSuccessful())
        {
            return entity.getBody();
        }
        return new CommonResult<>(444,"操作失败");
    }
}
